//
//  Status.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/3.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SDWebImage
///微博模型
class Status: NSObject {
    //微博创建时间
    var created_at: String?
    //微博ID
    var id: Int = 0
    //微博信息内容
    var text: String?
    //微博来源
    var source: String?
    //配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            if pic_urls?.count == nil {
                return
            }
            //实例化数组
            storedPictureURLs = [NSURL]()
            storedLargePictureURLs = [NSURL]()
            
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"]  {
                    storedPictureURLs?.append(NSURL(string: urlString as! String)!)
                    
                    let largeURLString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storedLargePictureURLs?.append(NSURL(string: largeURLString)!)
                }
            }
            
        }
    }
    
    //"保存"配图的 url 
    private var storedPictureURLs: [NSURL]?
    //大图的url
    private var storedLargePictureURLs: [NSURL]?
    
    //配图URL数组
    var pictureURLs: [NSURL]? {
        return retweeted_status == nil ? storedPictureURLs: retweeted_status?.storedPictureURLs
    }
    //大图UTR数组
    var largePictureURLs: [NSURL]? {
        return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs  
    }
    
    // 用户
    var user: User?
    //转发微博
    var retweeted_status: Status?
    //显示微博所需的行高
    var rowHeight: CGFloat?
    
    
    ///加载数据
   class func loadStatus (since_id: Int, max_id: Int, finished: (dataList: [Status]?, error: NSError?) -> ()) {
        NetworkTools.sharedTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil  {
                finished(dataList: nil, error: error)
                return
            }
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                //遍历数组,字典转模型
                var list = [Status]()
                
                for dict in array {
                   list.append(Status(dict: dict))
                }
                self.cacheWebImage(list, finished: finished)
//                finished(dataList: list, error: nil)
            }else {
                finished(dataList: nil, error: nil)
            }
            
        }
        
    }
    
    ///缓存网络图片, 保存后再刷新数据
    private class func cacheWebImage(list: [Status], finished: (dataList: [Status]?, error: NSError?) -> ()) {
        //创建队列
        let group = dispatch_group_create()
        //缓存图片大小
        var dataLength = 0
        //循环遍历数组
        for status in list {
            //判断是否有图片
            guard let urls = status.pictureURLs else {
                continue
            }
            
            //遍历urls数组
            for imageUrl in urls {
                //入组
                dispatch_group_enter(group)
                //缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
//                    print(image)
                    //将图片转换成二进制数据
                    if image != nil {
                    let imageDate = UIImagePNGRepresentation(image)
                    dataLength += imageDate!.length
                    }
                    dispatch_group_leave(group)
                })
            }
            
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            print("over")
            print("缓存图片的大小 \(dataLength / 1024) k")
            finished(dataList: list, error: nil)
        }
        
    }
    
    //MARK: 构造函数
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        //判断 key 是否有值, 如果是
        if key == "user" {
            // 判断value 是否是有效的字典
            if let dict = value as? [String: AnyObject] {
                user = User(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = Status(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let keys = ["created_at", "id", "text", "source", "pic_urls"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
}
